import React from 'react';
import { Breadcrumb,Layout,Input,Avatar, Form,Modal,Button, message} from 'antd';
import { HomeOutlined, MessageOutlined,EnterOutlined,QuestionCircleOutlined, PlusCircleOutlined} from  '@ant-design/icons'
import {Link} from 'react-router-dom'
import {GetUserName} from '../../../common/auth.js'
import UserList from '../../../components/UserList/index.js'
import News from '../../../components/News/index.js';
import http from '../../../service/http.js'
import config from '../../../config/index.js'
import "./index.css"

const {useState,useEffect}=React
const {Header, Sider, Content,Footer } = Layout;

let socket;
let newsListTo=[];
let usersTo;
let indexTo=0;
const socketUrl = config.socketUrl;
export default function QQ() {
  let [index,setIndex]=useState(0)
  let [headerMessage,setHeaderMessage]=useState('聊天室')
  let [my,setMy]=useState({})
  let [addVisible,setAddVisible]=useState(false)
  let [applyVisible,setApplyVisible]=useState(false)
  let [searchFriend,setSearchFriend]=useState({display:'none',padding:'5px',backgroundColor:'#e5e5e5',marginTop:'30px'})
  let [friendMessage,setFriendMessage]=useState({img:'',username:'',name:''})
  let [to,setTo]=useState({})
  let [users,setUsers]=useState([])
  let [noUser,setNoUser]=useState([])
  let [newsList,setNewsList]=useState([])
  let [lineUsers,setLineUsers] = useState([])
  useEffect(()=>{
    contentRef.current.scrollTop=contentRef.current.scrollHeight
  },[newsList])
  useEffect(()=>{
    http.getUser({username:GetUserName()}).then((res)=>{
      setMy(res.data)
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
    socket = new WebSocket(socketUrl+GetUserName())
    socket.onopen = function () {
      console.log("websocket已打开")
    }
    socket.onmessage = function (msg) {
      let data = JSON.parse(msg.data)
      if(data.type==="0"){
        setUsers(data.users)
        usersTo=data.users
      }
      else if(data.type==="1"){
        setLineUsers(data.lineUsers)
      }
      else if(data.type==="2"){
        setLineUsers(lineUsers.filter((item)=>{
          return item!==data.offLineUsers
        }))
      }
      else if(data.type==="3"){
        if(indexTo!==0&&usersTo[indexTo-1].username===data.from){
          newsListTo=[...newsListTo,{message:data.text,username:data.from,dateTime:new Date()}]
          setNewsList([...newsListTo])
        }
        let newUsers=usersTo.map((item)=>{
          if(item.username===data.from){
            item.message=data.text
          }
          return item;
        })
        setUsers(newUsers)
      }
      else if(data.type==="4"){
        newsListTo.push({message:data.text,name:data.name,img:data.img,dateTime:new Date()})
        setNewsList([...newsListTo])
      }
      else if(data.type==="5"){
        if(data.flag===true){
          message.success('申请成功')
        }else{
          message.info('你已经有该好友了或者已经提交过申请')
        }
      }
    }
    socket.onclose = function () {
        console.log("websocket已关闭");
      };
      //发生了错误事件
    socket.onerror = function () {
        console.log("websocket发生了错误");
      }
    // return socket=null
      // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])
  const [messageForm]=Form.useForm()
  const contentRef=React.useRef()
  return (
    <div style={{padding:'15px'}}>
      <Breadcrumb>
        <Breadcrumb.Item>
          <HomeOutlined />
          <Link to='/home'>首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <MessageOutlined />
          <Link to='/home/qq5'>QQ</Link>
        </Breadcrumb.Item>
      </Breadcrumb>
      <hr/>
      <Layout style={{minHeight:'70vh'}}>
        <Sider style={{backgroundColor:'#c0c0c0',color:'#ffffff',padding:'10px'}}>
          <div style={{display:'flex',backgroundColor:'#ffffff'}} className={index===0?'click':''} onClick={()=>{
            setIndex(0)
            indexTo=0
            setHeaderMessage('聊天室')
            setNewsList([])
            newsListTo=[]
          }}>
            <div style={{flex:"2",display:'flex',justifyContent:'center',alignItems:'center'}}><Avatar src={my.img}/></div>
            <div style={{flex:"4"}}>
              <h3 style={{fontSize:'1px',height:'45px',lineHeight:'45px',cursor:'default'}}>{my.name}</h3>
            </div>
            <span style={{flex:"3",fontSize:'1px',margin:0,padding:0,color:"#007acc",display:'flex',justifyContent:'center',alignItems:'center',cursor:'default'}}>我自己</span>
          </div>
          <div>好友列表</div>
          <div style={{height:'60vh',backgroundColor:'#ffffff',overflowY:'auto'}}>
            {
              users.length===0?'':users.map((item,i)=>{
                return <UserList user={item} key={item.username} newsId={item.newsId} index={index} i={i+1}
                setTo={()=>{
                  setTo(item)
                }}
                changeIndex={(i)=>{
                  setIndex(i)
                  indexTo=i
                }}
                changeHeaderMessage={()=>{
                  setHeaderMessage(item.name)
                }}
                changeNewsList={(data)=>{
                  setNewsList(data)
                  newsListTo=data
                }}
                lineUsers={lineUsers}
                ></UserList>
              })
            }
          </div>
        </Sider>
        <Modal title="添加好友" footer={null} visible={addVisible} onCancel={()=>{setAddVisible(false);setSearchFriend({display:'none',padding:'5px',backgroundColor:'#e5e5e5',marginTop:'30px'})}}>
          <Input.Search placeholder="按手机号搜索" onSearch={(value)=>{
            http.getUser({username:value}).then((res)=>{
              if(res.data){
                setFriendMessage(res.data)
                setSearchFriend({display:'flex',padding:'5px',backgroundColor:'#e5e5e5',marginTop:'30px'})
              }
              else{
                message.info('查找失败,没有该用户')
              }
            })
          }} enterButton />
          <div style={searchFriend}>
            <div style={{flex:'1',display:'flex',justifyContent:'center',alignItems:'center'}}><Avatar src={friendMessage.img}></Avatar></div>
            <div style={{flex:'2',display:'flex',justifyContent:'center',alignItems:'center'}}>{friendMessage.name}</div>
            <div style={{flex:'2',display:'flex',justifyContent:'center',alignItems:'center'}}>{friendMessage.username}</div>
            <Button type='primary' style={{flex:'1'}} onClick={()=>{
              http.applyFriend({username1:my.username,username2:friendMessage.username}).then((res)=>{
                if(res.data===true){
                  message.success('申请成功')
                }else{
                  message.info('你已经有该好友了或者已经提交过申请')
                }
              })
            }}>添加</Button>
          </div>  
        </Modal>
        <Modal title="申请列表" footer={null} visible={applyVisible} onOk={()=>{}} onCancel={()=>{setApplyVisible(false)}}>
          {
            noUser.length===0?'暂无申请好友':noUser.map((item)=>{
              return(
                <div style={{display:'flex',padding:'5px',backgroundColor:'#e5e5e5',marginTop:'30px'}} key={item.username}>
                  <div style={{flex:'1',display:'flex',justifyContent:'center',alignItems:'center'}}><Avatar src={item.img}></Avatar></div>
                  <div style={{flex:'2',display:'flex',justifyContent:'center',alignItems:'center'}}>{item.name}</div>
                  <div style={{flex:'2',display:'flex',justifyContent:'center',alignItems:'center'}}>{item.username}</div>
                  <Button type='primary' danger style={{flex:'1',marginRight:'10px'}} onClick={()=>{
                      let data = {
                        type:'3',
                        username:item.username
                      }
                      if(socket){
                        socket.send(JSON.stringify(data));
                        message.success('拒绝成功')
                        setApplyVisible(false)
                      }
                  }}>拒绝</Button>
                  <Button type='primary' style={{flex:'1'}} onClick={()=>{
                      let data = {
                        type:'2',
                        username:item.username
                      }
                      if(socket){
                        socket.send(JSON.stringify(data));
                        message.success('添加成功')
                        setApplyVisible(false)
                      }
                  }}>同意</Button>
                </div> 
              )
            })
          } 
        </Modal>
        <Layout style={{backgroundColor:"#c0c0c0",paddingRight:'10px',paddingBottom:'10px',paddingTop:'10px'}}>
          <Header style={{height:'30px',lineHeight:'30px',backgroundColor:'#ffffff',padding:0,margin:0}}>
            <div style={{float:'right'}} onClick={()=>{
              http.getNoUser({username:my.username}).then((res)=>{
                setNoUser(res.data)
              })
              setApplyVisible(true)
            }}
            ><QuestionCircleOutlined style={{fontSize:'20px',marginRight:'15px'}}/></div>
            <div style={{float:'left'}} onClick={()=>{
              setAddVisible(true)
            }}
            ><PlusCircleOutlined style={{fontSize:'20px',marginLeft:'15px'}}/></div>
            <div style={{margin:'0 15px',borderBottom:'1px #d5d5d5 solid',textAlign:"center",height:'100%'}}>
              {headerMessage}
              {index===0?"("+lineUsers.length+")":''}
            </div>
          </Header>
          <Content>
            <div ref={contentRef}  style={{backgroundColor:'#ffffff',overflowY:'auto',height:'58vh'}}>
              {
                newsList.length===0?'':newsList.map((item,index)=>{
                  if(item.name){
                    let data = {
                      message:item.message,
                      name:item.name,
                      img:item.img
                    }
                    if(item.name===my.name){
                      return <News type="0" data={data} key={item.dateTime}></News>
                    }
                    else{
                      return <News type="1" data={data} key={item.dateTime}></News>
                    }
                  }
                  if(item.username===GetUserName()){
                    let data = {
                      message:item.message,
                      name:my.name,
                      img:my.img
                    }
                    return <News type="0" data={data} key={item.dateTime}></News>
                  }
                  let data = {
                      message:item.message,
                      name:to.name,
                      img:to.img
                  }
                  return <News type="1" data={data} key={item.dateTime}></News>
                })
              }
            </div>
          </Content>
          <Footer style={{height:'30px',lineHeight:'30px',textAlign:"center",padding:"0",backgroundColor:'#ffffff',marginTop:'10px',borderRadius:'10px'}}>
            <Form form={messageForm} name='messageForm'>
              <Form.Item name="inputMessage">
                <Input placeholder="请输入内容" bordered={false} suffix={<EnterOutlined />}
                  onPressEnter={(e)=>{
                    let str = e.target.value
                    messageForm.resetFields()
                    if(index===0){
                      // 群聊
                      let message = {
                        type:'1',
                        img:my.img,
                        name:my.name,
                        text:str
                      }
                      if(socket){
                        socket.send(JSON.stringify(message));
                      }
                    }
                    else{
                      //单聊
                      let newUsers=users.map((item)=>{
                        if(item.username===to.username){
                          item.message=str
                        }
                        return item;
                      })
                      setUsers(newUsers)
                      usersTo=newUsers
                      let message = {
                        type:'0',
                        to:to.username,
                        newsId:to.newsId,
                        text:str
                      }
                      if(socket){
                        socket.send(JSON.stringify(message));
                        setNewsList([...newsList,{message:str,username:my.username,dateTime:new Date()}])
                        newsListTo=[...newsList,{message:str,username:my.username,dateTime:new Date()}]
                      }
                    }
                  }}
                />
              </Form.Item>
            </Form>
          </Footer>
        </Layout>
      </Layout>
    </div>
  )
}